package com.app.util;

import java.io.File;
import java.io.IOException;
import java.util.LinkedHashSet;

import com.app.util.file.obj.ObjectReader;
import com.app.util.file.obj.ObjectWriter;

public class StoragedLinkedHashSet<T> extends LinkedHashSet<T> {

	private static final long serialVersionUID = 3823905278926337270L;
	private transient boolean changed;
	private transient File file; 

	@SuppressWarnings("unchecked")
	public static StoragedLinkedHashSet fromFile(File file) throws IOException, ClassNotFoundException {
		StoragedLinkedHashSet storagedMap;
		if (file.exists() && file.length() > 0) {
			ObjectReader or = new ObjectReader(file);
			try {
				storagedMap = (StoragedLinkedHashSet) or.next();
			} finally {
				or.close();
			}
		} else {
			storagedMap = new StoragedLinkedHashSet();
		}
		if (null != storagedMap) {
			storagedMap.file = file;
		}
		return storagedMap;
	}

	private StoragedLinkedHashSet() {
	}

	public boolean add(T obj) {
		boolean o = super.add(obj);
		changed = true;
		return o;
	}

	public void save() throws IOException {
		ObjectWriter ow = new ObjectWriter(file);
		try {
			ow.writeObject(this);
			changed = false;
		} finally {
			ow.close();
		}
	}

	public boolean isChanged() {
		return changed;
	}
}
